package com.bestcem.xm.openplatform.grpc.client;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.deliver.grpc.v1.services.*;
import com.bestcem.xm.openplatform.convert.grpc.OpenplatformGrpcConvertMapper;
import com.bestcem.xm.openplatform.grpc.client.dto.DeliverDto;
import com.bestcem.xm.openplatform.grpc.client.dto.DeliverExtDeliverMappingDto;
import com.bestcem.xm.openplatform.grpc.client.dto.DeliverExtParamsDto;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Slf4j
@Component
public class DeliverGrpcClient {

    @GrpcClient(GrpcClientNames.DS_DELIVER)
    private BaseDeliverServiceGrpc.BaseDeliverServiceBlockingStub baseStub;

    private final OpenplatformGrpcConvertMapper grpcConvertMapper;

    public DeliverGrpcClient(OpenplatformGrpcConvertMapper grpcConvertMapper) {
        this.grpcConvertMapper = grpcConvertMapper;
    }

    public List<DeliverExtParamsDto> listDeliverExtparams(JSONObject params) {
        ListDeliverExtparamsRequest.Builder builder = ListDeliverExtparamsRequest.newBuilder();
        builder.setSearch(Optional.ofNullable(params.getString("search")).orElse(""));
        params.remove("search");

        String statusStr = params.getString("status");
        if (StrUtil.isNotEmpty(statusStr) && JSONUtil.isTypeJSONArray(statusStr)) {
            builder.addAllStatus(JSONArray.parseArray(statusStr).toJavaList(Integer.class));
            params.remove("status");
        } else {
            builder.addAllStatus(Lists.newArrayList());
        }

        DeliverExtParamsDto requestDto = JSONObject.toJavaObject(params, DeliverExtParamsDto.class);
        builder.setDeliverExtparams(grpcConvertMapper.toGrpcDeliverExtparams(requestDto));

//        builder.addAllFields(null);
        try {
            DeliverExtparamsSearchResponse response = baseStub.listDeliverExtparams(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[openplatform] listDeliverExtparams Error, ErrorMsg: {}", response);
                return null;
            }
            return grpcConvertMapper.toDeliverExtParamsDtoList(response.getDeliverExtparamsListList());
        } catch (Exception e) {
            log.error("[openplatform] ex listDeliverExtparams Error, ErrorMsg:", e);
            return null;
        }
    }

    public List<DeliverExtDeliverMappingDto> listExtDeliverMapping(JSONObject params) {
        ListExtDeliverMappingRequest.Builder builder = ListExtDeliverMappingRequest.newBuilder();
        ExtDeliverMapping.Builder extDeliverMappingBuilder = ExtDeliverMapping.newBuilder();
        extDeliverMappingBuilder.setOrgId(Optional.ofNullable(params.getString("org_id")).orElse(""));
        extDeliverMappingBuilder.setSystemNo(Optional.ofNullable(params.getString("system_no")).orElse(""));
        extDeliverMappingBuilder.setConditionNo(Optional.ofNullable(params.getString("condition_no")).orElse(""));
        builder.setSearch(Optional.ofNullable(params.getString("search")).orElse(""));
        builder.setExtDeliverMapping(extDeliverMappingBuilder);
        params.remove("search");
//        builder.addAllFields(null);
        try {
            ExtDeliverMappingSearchResponse response = baseStub.listExtDeliverMapping(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[openplatform] listExtDeliverMapping Error, ErrorMsg: {}", response);
                return null;
            }
            return grpcConvertMapper.toDeliverExtDeliverMappingDtoList(response.getExtDeliverMappingListList());
        } catch (Exception e) {
            log.error("[openplatform] ex listExtDeliverMapping Error, ErrorMsg:", e);
            return null;
        }
    }

    public List<DeliverDto> listDeliverByIds(List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return null;
        }
        ListDeliverByIdsRequest.Builder builder = ListDeliverByIdsRequest.newBuilder();
        builder.addAllIds(ids);
        try {
            DeliverSearchResponse response = baseStub.listDeliverByIds(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[openplatform] listDeliverByIds, ids = {} Error; ErrorMsg: {}", ids, response);
                return null;
            }
            List<Deliver> deliverList = response.getDeliverListList();
            List<DeliverDto> deliverDeliverList = new ArrayList<>();
            deliverList.forEach(a -> deliverDeliverList.add(grpcConvertMapper.toDeliverDto(a)));
            return deliverDeliverList;
        } catch (Exception e) {
            log.error("[openplatform] exp listDeliverByIds, ids = {} Error; ErrorMsg: {}", ids, e.getMessage(), e);
            return null;
        }
    }
}
